package com.gc.ykqx.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gc.ykqx.R;
import com.gc.ykqx.service.entity.GridItem;
import com.gc.ykqx.service.entity.Past24;
import com.gc.ykqx.service.entity.PreInt;
import com.gc.ykqx.service.entity.TemInt;
import com.gc.ykqx.service.entity.WindInt;
import com.gc.ykqx.service.util.DataParse;
import com.gc.ykqx.service.presenter.PastPresenter;
import com.gc.ykqx.service.view.PastView;
import com.gc.ykqx.ui.adapter.BaseGridViewAdapter;
import com.gc.ykqx.ui.custom.BaseActivity;
import com.gc.ykqx.service.util.Constant;
import com.gc.ykqx.service.util.ParseUtil;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.victor.loading.rotate.RotateLoading;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DetailsActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, AdapterView.OnItemClickListener {

    private static final String TAG = "DetailsActivity";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.third_menu)
    GridView gridView;
    @BindView(R.id.pre_menu)
    RadioGroup rgMenu;
    @BindView(R.id.tem_max)
    TextView temMax;
    @BindView(R.id.tem_min)
    TextView temMin;
    @BindView(R.id.tem_chart)
    LineChart temChart;
    @BindView(R.id.tem_layout)
    RelativeLayout temLayout;
    @BindView(R.id.pre_tv)
    TextView preTv;
    @BindView(R.id.pre_chart)
    BarChart preChart;
    @BindView(R.id.pre_layout)
    RelativeLayout preLayout;
    @BindView(R.id.wind_max)
    TextView windMax;
    @BindView(R.id.wind_chart)
    LineChart windChart;
    @BindView(R.id.wind_layout)
    RelativeLayout windLayout;
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;
    Unbinder unbinder;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.main_layout)
    RelativeLayout mainLayout;

    private String siteId = Constant.YK_STA_ID;//当前站号
    private String type = Constant.Type.TEM;//TEM PRE WIND
    private List<GridItem> gridItemList;//tab 名字
    private BaseGridViewAdapter adapter;//适配器
    private String[] xNames = new String[24];//横坐标
    private Float preSum;//降水统计
    private PastPresenter pastPresenter;
    private Context mContext;
    List<TemInt> temIntList;
    List<PreInt> preIntList;
    List<WindInt> windIntList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        unbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        mContext = this;
        pastPresenter = new PastPresenter(mContext);
        pastPresenter.attachView(pastView);
        pastPresenter.onCreate();

        Intent intent = getIntent();
        siteId = intent.getStringExtra(Constant.TransmissionKey.SITE_ID);
        String selectId = intent.getStringExtra(Constant.TransmissionKey.SELECT_ID);
        if (selectId.contains("n0")) {
            type = Constant.Type.TEM;
        } else if (selectId.contains("n4")) {
            type = Constant.Type.WIND;
        } else {
            type = Constant.Type.PRE;
        }
        gridItemList = DataParse.excludeItem((List<GridItem>) intent.getSerializableExtra(Constant.TransmissionKey.ITEM_LIST));
        //把武义缙云的站点放到后面
        if (gridItemList != null) {
            for (int i = 0; i < gridItemList.size(); i++) {
                GridItem gridItem = gridItemList.get(i);
                if (gridItem.isChecked() == true) {
                    siteId = gridItem.getSiteId();
                    break;
                }
            }
            adapter = new BaseGridViewAdapter(this, gridItemList);
            gridView.setAdapter(adapter);
            rgMenu.setOnCheckedChangeListener(this);
            gridView.setOnItemClickListener(DetailsActivity.this);
            loadData();
        }
    }

    private PastView pastView = new PastView() {
        @Override
        public void onSuccess(Past24 past24) {
            if (rotateloading != null) {
                rotateloading.stop();
            }
            if (past24.getReturnCode() == Constant.Response.SUCCESS_CODE && past24.getRowCount() == 24) {
                Map<String, List> listMap = DataParse.parsePast(past24.getDS());
                temIntList = listMap.get(Constant.Type.TEM);
                preIntList = listMap.get(Constant.Type.PRE);
                windIntList = listMap.get(Constant.Type.WIND);
                setTemChart();
                setPreChart();
                setWindChart();
                showChart();
            }

        }

        @Override
        public void onError(String result) {

        }
    };


    private void showChart() {
        switch (type) {
            case Constant.Type.TEM:
                temLayout.setVisibility(View.VISIBLE);
                preLayout.setVisibility(View.GONE);
                windLayout.setVisibility(View.GONE);
                break;
            case Constant.Type.PRE:
                temLayout.setVisibility(View.GONE);
                preLayout.setVisibility(View.VISIBLE);
                windLayout.setVisibility(View.GONE);
                break;
            case Constant.Type.WIND:
                temLayout.setVisibility(View.GONE);
                preLayout.setVisibility(View.GONE);
                windLayout.setVisibility(View.VISIBLE);
                break;
        }
    }
      /*
    设置温度
     */

    private void setTemChart() {
        if (temIntList != null && temIntList.size() > 0) {
            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < temIntList.size(); i++) {
                TemInt temInt = temIntList.get(temIntList.size() - i - 1);
                if (temInt != null) {
                    String temValue = temInt.getDryBulTemp();
                    String time = temInt.getObservTimes();
                    if (!TextUtils.isEmpty(temValue)) {
                        // entries.add(new Entry(i, Float.parseFloat(temValue)));
                        entries.add(new Entry(i, Float.parseFloat(temValue)));
                        xNames[i] = ParseUtil.getHourByTime(time);
                    } else {
                        entries.add(new Entry(i, 0));
                    }
                } else {
                    entries.add(new Entry(i, 0));
                }
            }
            LineDataSet dataSet = new LineDataSet(entries, "24小时温度");
            LineData data = new LineData(dataSet);
            //  data.setValueTextSize(10f);
            //   data.setValueTextColor(FactorType.RED);
            data.setValueTextColor(Color.RED);
            dataSet.setLineWidth(2f);
            dataSet.setDrawValues(true);
            dataSet.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    if (value == 0.0) {
                        return "";
                    } else {
                        DecimalFormat mFormat = new DecimalFormat("#0.0");
                        return mFormat.format(value);
                    }
                }
            });
            temChart.setData(data);
            setChart(temChart);
            temMax.setText("最高温度: " + temChart.getYMax() + "℃");
            temMin.setText("最低温度: " + temChart.getYMin() + "℃ ");
        }
    }

    /*
      设置降水
       */
    private void setPreChart() {
        if (preIntList != null && preIntList.size() > 0) {
            List<IBarDataSet> dataSets = new ArrayList<>();
            List<BarEntry> entries = new ArrayList<>();
            for (int i = 0; i < preIntList.size(); i++) {
                PreInt preInt = preIntList.get(i);
                if (preInt != null) {
                    String preValue = preInt.getPrecipitation();
                    if (!TextUtils.isEmpty(preValue)) {
                        entries.add(new BarEntry(i, Float.parseFloat(preValue)));
                    } else {
                        entries.add(new BarEntry(i, 0));
                    }
                } else {
                    entries.add(new BarEntry(i, 0));
                }
            }
            dataSets.add(new BarDataSet(entries, "24小时降水"));
            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setValueTextColor(Color.RED);
            data.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    if (value == 0.0) {
                        return "";
                    } else {
                        DecimalFormat mFormat = new DecimalFormat("#0.0");
                        return mFormat.format(value);
                    }
                }
            });
            preChart.setData(data);
            setChart(preChart);
            getPreSum();//获取累加值
            preTv.setText("降水合计：" + ParseUtil.saveOne(preSum + "") + "mm");
        }
    }

    /*
    设置风速
     */
    private void setWindChart() {
        if (windIntList != null && windIntList.size() > 0) {
            List<Entry> entries = new ArrayList<>();
            for (int i = 0; i < windIntList.size(); i++) {
                WindInt windInt = windIntList.get(i);
                if (windInt != null) {
                    String wind = windInt.getWindVelocity();
                    // String hour=windInt.getObservTimes().substring(8,10);
                    if (!TextUtils.isEmpty(wind)) {
                        entries.add(new Entry(i, Float.parseFloat(wind)));
                    } else {
                        entries.add(new Entry(i, 0));
                    }
                } else {
                    entries.add(new Entry(i, 0));
                }
            }
            LineDataSet dataSet = new LineDataSet(entries, "24小时风速");
            LineData data = new LineData(dataSet);
            data.setValueTextSize(10f);//数值大小
            data.setValueTextColor(Color.RED);
            dataSet.setLineWidth(2f);//折线宽度
            dataSet.setValueFormatter(new IValueFormatter() {
                @Override
                public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                    if (value == 0.0) {
                        return "";
                    } else {
                        DecimalFormat mFormat = new DecimalFormat("#0.0");
                        return mFormat.format(value);
                    }
                }
            });
            windChart.setData(data);
            setChart(windChart);
            windMax.setText("极大风速：" + windChart.getYMax() + "m/s");
        }
    }

    /*
    设置图表其他选项
     */
    private void setChart(BarLineChartBase chart) {
        setX(chart);
        setY(chart);
        setAttr(chart);
        chart.setVisibleXRangeMaximum(24);
        Description desc = new Description();
        desc.setText("");
        chart.setDescription(desc);
        chart.invalidate();
        chart.notifyDataSetChanged();
    }

    /*
    设置横坐标
     */
    private void setX(BarLineChartBase chart) {
        XAxis xAxis = chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setTextSize(10f);
        xAxis.setDrawAxisLine(false);//
        xAxis.setDrawGridLines(true);//画网格
        final String[] quarters = xNames;
        IAxisValueFormatter formatter = new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return quarters[(int) value];
            }
        };
        xAxis.setGranularity(1f); // minimum axis-step (interval) is 1
        xAxis.setValueFormatter(formatter);
    }

    /*
    设置纵坐标
     */
    private void setY(BarLineChartBase chart) {
        YAxis left = chart.getAxisLeft();
        left.setDrawLabels(true); // no axis labels
        left.setDrawAxisLine(false); // no axis line
        left.setDrawGridLines(true); // no grid lines
        left.setDrawZeroLine(false); // draw a zero line
        if (chart == preChart) {
            left.setAxisMinimum(0);
        }
        chart.getAxisRight().setEnabled(false); // no right axis
    }

    /*
    设置图表属性
     */
    private void setAttr(BarLineChartBase chart) {
        chart.setTouchEnabled(true);//允许与用户交互
        chart.setDragEnabled(true);//拖拽
        chart.setScaleXEnabled(true);
        chart.setScaleYEnabled(false);
        chart.setPinchZoom(false);
        chart.setDoubleTapToZoomEnabled(false);
    }

    /*
    选项监听
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_tem:
                type = Constant.Type.TEM;
                break;
            case R.id.rb_rain:
                type = Constant.Type.PRE;
                break;
            case R.id.rb_wind:
                type = Constant.Type.WIND;
                break;
        }
        showChart();
    }

    /*
    gridView监听
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        GridItem item = gridItemList.get(position);
        if (item.getSiteId().equals(siteId)) {
            return;
        } else {
            for (int i = 0; i < gridItemList.size(); i++) {
                if (i == position) {
                    GridItem gridItem = gridItemList.get(i);
                    siteId = gridItem.getSiteId();
                    tvTitle.setText(gridItem.getName());
                    gridItem.setChecked(true);
                } else {
                    GridItem gridItem = gridItemList.get(i);
                    gridItem.setChecked(false);
                }
            }
            adapter.notifyDataSetChanged();
            loadData();
        }

    }

    /*
    加载数据
     */
    private void loadData() {
        rotateloading.start();
        pastPresenter.getPastInfo(siteId);
    }

    /*
    计算降水量
     */
    public void getPreSum() {
        preSum = 0f;
        if (preIntList != null) {
            for (int i = 0; i < preIntList.size(); i++) {
                PreInt preInt = preIntList.get(i);
                String value = preInt.getPrecipitation();
                if (!TextUtils.isEmpty(value) && !value.equals(Constant.NO_PRE_FLAG) && !value.equals(Constant.NO_DATA_FLAG)) {
                    preSum += Float.parseFloat(value);
                }
            }
        }
    }

    /*
    返回按钮
     */
    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
